package com.wayne.blog.interceptor;

import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 请求ID拦截器
 * @author Lang
 * @since 2024/06/06
 */
public class RequestIdInterceptor implements HandlerInterceptor {
    
    private static final String REQUEST_ID = "requestId";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        MDC.put(REQUEST_ID, requestId);
        response.setHeader(REQUEST_ID, requestId);
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove(REQUEST_ID);
    }
} 